// 1. 引入 mysql 模块
let mysql = require("mysql");
//2. 创建一个连接池
let pool = mysql.createPool({
        connectionLimit: 20,
        host: "localhost",
        port: 3306,
        user: "root",
        password: "root123!@#",
        database: "myshop"
    })
    /* 3. 定义一个数据库查询的方法 */

function query(sql, values, callback) {
    console.log("开始查询:", sql, values);
    pool.getConnection(function(err, connection) {
        if (err) throw err;
        connection.query(sql, values, function(err, results, fields) {
            callback(err, results, fields);
            // 释放连接
            connection.release();
        })
    })
}

function queryWithPromise(sql, values) {
    console.log("开始查询:", sql, values);
    return new Promise(function(resolve, reject) {
        pool.getConnection(function(err, connection) {
            if (err) throw err;
            connection.query(sql, values, function(err, results, fields) {
                resolve({ err, results, fields });
                connection.release();
            })
        })
    })
}

/* 根据 cat_id 返回菜单的数据 */
function query_cat(cat_id) {
    let sql = "select * from menu where cat_id = ?";
    return new Promise(function(resolve, reject) {
        query(sql, [cat_id], function(err, results, fileds) {
            resolve(results);
        })
    })
}
exports.query = query;
exports.query_cat = query_cat;
exports.queryWithPromise = queryWithPromise;